<!DOCTYPE html>
<html>
<body>
<script src="../resources/testharness.js"></script>
<script src="../resources/testharnessreport.js"></script>
<script>

var changeTest = async_test("Test that window's orientationchange event is fired when the orientation changes.");
var noChangeTest = async_test("Test that window's orientationchange event is not fired when the orientation does not change.");

if (window.internals && internals.runtimeFlags.orientationEventEnabled) {
  var orientations = [
    'portrait-primary',
    'portrait-secondary',
    'landscape-primary',
    'landscape-secondary'
  ];

  var orientationAngles = [
      0,
      180,
      90,
      -90
  ];

  var currentIndex = 0;
  // Count the number of calls received from the EventHandler set on window.onorientationchange
  var orientationChangeEventHandlerCalls = 0;
  // Count the number of calls received from the listener set with window.addEventListener("orientationchange",...)
  var orientationChangeEventListenerCalls = 0;

  function getNextIndex() {
    return (currentIndex + 1) % orientationAngles.length;
  }

  window.onorientationchange = function(event) {
    orientationChangeEventHandlerCalls++;
  };

  window.addEventListener('orientationchange', function() {
    orientationChangeEventListenerCalls++;
  });

  function runNoChangeTest() {
    testRunner.setMockScreenOrientation(orientations[currentIndex]);

    setTimeout(function() {
      noChangeTest.step(function() {
        assert_equals(window.orientation, orientationAngles[currentIndex]);
        assert_equals(orientationChangeEventHandlerCalls, 4);
        assert_equals(orientationChangeEventListenerCalls, 4);
      });

      noChangeTest.done();
    });
  }

  var i = 0;
  function runChangeTest() {
    testRunner.setMockScreenOrientation(orientations[getNextIndex()]);
    currentIndex = getNextIndex();

    setTimeout(function() {
      changeTest.step(function() {
        assert_equals(window.orientation, orientationAngles[currentIndex]);
        assert_equals(orientationChangeEventHandlerCalls, i + 1);
        assert_equals(orientationChangeEventListenerCalls, i + 1);
      });

      ++i;
      if (i == 4) {
        changeTest.done();
        runNoChangeTest();
      } else {
        runChangeTest();
      }
    });
  }

  runChangeTest();
} else {
  console.error("This test requires window.internals and the orientationchange event to be enabled.");
  changeTest.done();
  noChangeTest.done();
}

</script>
</body>
</html>
